/*
 * @Autor: dingxiaolin
 * @Date: 2020-04-14 13:30:31
 * @LastEditors: dingxiaolin
 * @LastEditTime: 2020-04-18 10:20:41
 */
const getRawBody = require('raw-body');
const request = require('request-promise')
const CryptoJS = require('crypto-js')
const WebSocket = require('ws')
var fs = require('fs')
var log = require('log4node')
var ws;
// 在控制台-我的应用-在线语音合成（流式版） 系统配置 
const config = {
    hostUrl: "wss://tts-api.xfyun.cn/v2/tts",
    host: "tts-api.xfyun.cn",
    appid: "5ba07e14",
    apiSecret: "5e9ccd6f81df00aa9e689426edbd216a",
    apiKey: "1bc667e0bf8bbeaf66eeab18275fbe21",
    text: "这是一个例子，请输入您要合成的文本",
    uri: "/v2/tts",
}

// 初始化入口函数
module.exports.initializer = function (context, callback) {
    console.log('111');
    connect();
    callback(null, '');
};

function connect() {
    // 获取当前时间 RFC1123格式
    let date = (new Date().toUTCString())
    // 设置当前临时状态为初始化
    let wssUrl = config.hostUrl + "?authorization=" + getAuthStr(date) + "&date=" + date + "&host=" + config.host
    ws = new WebSocket(wssUrl)
    // 鉴权签名
    function getAuthStr(date) {
        let signatureOrigin = `host: ${config.host}\ndate: ${date}\nGET ${config.uri} HTTP/1.1`
        let signatureSha = CryptoJS.HmacSHA256(signatureOrigin, config.apiSecret)
        let signature = CryptoJS.enc.Base64.stringify(signatureSha)
        let authorizationOrigin = `api_key="${config.apiKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${signature}"`
        let authStr = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(authorizationOrigin))
        return authStr
    }
}


// 传输数据
function send(text) {
    let frame = {
        // 填充common
        "common": {
            "app_id": config.appid
        },
        // 填充business
        "business": {
            "aue": "raw",
            "auf": "audio/L16;rate=16000",
            "vcn": "xiaoyan",
            "tte": "UTF8"
        },
        // 填充data
        "data": {
            "text": Buffer.from(text).toString('base64'),
            "status": 2
        }
    }
    ws.send(JSON.stringify(frame))
}

// 入口函数
module.exports.handler = function (req, resp, context) {
    console.log('222')
    getRawBody(req, async (err, body) => {
        if (req.queries.text) {
            connect();
            // 连接建立完毕，读取数据进行识别
            ws.on('open', () => {
                log.info("websocket connect!")
                send(req.queries.text)
            })
            // 得到结果后进行处理，仅供参考，具体业务具体对待
            ws.on('message', (data, err) => {
                if (err) {
                    log.error('message error: ' + err)
                    return
                }

                let res = JSON.parse(data)

                if (res.code != 0) {
                    log.error(`${res.code}: ${res.message}`)
                    ws.close()
                    return
                }

                let audio = res.data.audio
                let audioBuf = Buffer.from(audio, 'base64')
                let aa = [];
                aa.push(...Array.from(audioBuf))
                if (res.code == 0 && res.data.status == 2) {
                    sendResp({
                        data: aa
                    })
                    ws.close()
                }
            })
            // 资源释放
            ws.on('close', () => {
                log.info('connect close!')
            })
            // 连接错误
            ws.on('error', (err) => {
                log.error("websocket connect err: " + err)
            })
        } else {
            sendResp({
                data: "请输入转换文字"
            })
        }
    });

    // 返回
    sendResp = (data) => {
        resp.setHeader('content-type', 'application/json');
        try {
            resp.send(JSON.stringify({
                success: true,
                data: data
            }));
        }
        catch (err) {
            resp.send(JSON.stringify({
                success: false,
                data: err.message
            }));
        }
    }
    // 保存文件
    // function save(data) {
    //     fs.writeFile('./text.mp3', data, { flag: 'a' }, (err) => {
    //         if (err) {
    //             log.error('save error: ' + err)
    //             return
    //         }

    //         log.info('文件保存成功')
    //     })
    // }


}